import { dark } from "@/styles/dark"
import { light } from "@/styles/light"
import { TypedStorageDecoder, TypedStorageEncoder, TypedStorageOptions } from "@nsb/common-tools"
import { ThemeConfig } from "antd"

export enum LightType {
  min = 0,
  light = 0,
  dark = 1,
  system = 2,
  max = 2
}

export const system_dark: MediaQueryList | undefined = window.matchMedia?.("(prefers-color-scheme: dark)")
export const lightConfigs: Record<LightType, ThemeConfig> = {
  [LightType.light]: light,
  [LightType.dark]: dark,
  [LightType.system]: system_dark?.matches ? dark : light
}
export const lightClassName: Record<LightType, string> = {
  [LightType.light]: 'app_light',
  [LightType.dark]: 'app_dark',
  [LightType.system]: system_dark?.matches ? 'app_dark' : 'app_light'
}
system_dark.addEventListener('change', () => {
  lightConfigs[LightType.system] = system_dark?.matches ? dark : light;
  lightClassName[LightType.system] = system_dark?.matches ? 'app_dark' : 'app_light'
})

const encoder: TypedStorageEncoder<LightType | null> = data => '' + data;
const decoder: TypedStorageDecoder<LightType | null> = raw => {
  const num = Number(raw)
  if (Number.isNaN(num)) return LightType.min;
  else if (num < LightType.min) return LightType.min;
  else if (num > LightType.max) return LightType.max;
  else return num
}
export const lightTypeOptions: TypedStorageOptions<LightType | null> = {
  defaultValue: LightType.light,
  encoder: encoder,
  decoder: decoder,
}
